package com.zhouixi.ras_js_java.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhouixi.ras_js_java.utils.RetResponse;
import com.zhouixi.ras_js_java.utils.RetResult;
import com.zhouixi.ras_js_java.utils.SecurityUtil;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.SM2;

@Controller
public class WebController {

    private final static Logger log = LoggerFactory.getLogger(WebController.class);


    private final static String publicKey  = "PUBLIC_KEY";
    private final static String privateKey = "PRIVATE_KEY";

    public static final String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCymjHmrddprC6gCzzXQa8YfIrGdKFzVBx0X74qr2Mvuz8D4d9vzJ9Xx5pQnQMVUJQvbAWE+izUR7/xkDc/Zka4/Mvd2rdqmqRoLoslMGBS+KNrPOWUlyhI8keb2n+IfapV4x8/u5eHD6Voz3rBcTV7IMNoqRxsmP/J+pAaLuDIFQIDAQAB";
    public static final String priKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALKaMeat12msLqALPNdBrxh8isZ0oXNUHHRfviqvYy+7PwPh32/Mn1fHmlCdAxVQlC9sBYT6LNRHv/GQNz9mRrj8y93at2qapGguiyUwYFL4o2s85ZSXKEjyR5vaf4h9qlXjHz+7l4cPpWjPesFxNXsgw2ipHGyY/8n6kBou4MgVAgMBAAECgYASD1uKavvEWL/iOSCu15qADF/wD20f/1pdPi05ncCW3AVUPCve3z8hnjJxgl8EccB6Rx8Lwkx0LskvARlFFO+Dq5v7/jZ5RFr238SEPaf4FjKYB1fwinu4yL67O1OlC4AFOxD0Ok+DgPPV5/VnndFdX07fAe2c+10RhnIX7i+DJQJBALxEg9bbj1K8FDzrajbebmza/4Xsc4rIrlq+T0tinmix3A8IHEGmu1MZfP6n1CVHfCcB5uExCCHc1DYa6JcuiCMCQQDy24C27cMk0pvr7iYMxoxFN++3IP/jOPa0wlsyj4PI1CK2/raRja3HxlW/KHhHN7HEZg7ThepRlh6x+AS7hxZnAkAw9lCjTC6WAbvxq/fPlUF6penWVowmB9LwXpYYsOkpqTfl4OIYYNhO4E4VnGgb2d979Y6p+ip3RAsclxruVnepAkBeMp2+VoK2qaoo3PqNQgXuYz/rvDUEoXevrSNKfTgUkZPVfv65fkbFkjx4JO5iUUv2bc+aY/r7IktNpHHRexhJAkAmvM8I/lQ9v9XC1boqPdb8HYaLa2+IYjHglYgnfX7aoqpv/DVgmPJMCxjP+BPVncugGrBxBV7F1RL/v/cHX2G+";


    public static final String pubKeySm2 = "0456b2cd60ec7763668c673ea92ad495e5a363bafb0ef23cfc70877cd2ef9205171f92b018d08d4de404bf1efcc0b60ba5b3f1eac9157495cf269a13ce088effbe";
    public static final String priKeySm2 = "6f637bc9c3383561ee9221450312ff11a863a301fc40c66e76b58788004eafdd";

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/sm2")
    public String sm2() {
        return "sm2";
    }


    @RequestMapping("/decrypt")
    @ResponseBody
    public RetResult decrypt(byte[] encrypt) throws Exception {
        File       file = ResourceUtils.getFile("classpath:keys/secret_key.txt");
        Properties pro  = new Properties();//创建集合
        pro.load(new FileInputStream(file));

        System.out.println("PUBLIC_KEY" + pro.get("PUBLIC_KEY"));
        System.out.println("PRIVATE_KEY" + pro.get("PRIVATE_KEY"));

        String decryptRSADefault = SecurityUtil.decryptRSADefault(pro.get("PRIVATE_KEY").toString(), new String(encrypt, "UTF-8"));
        System.out.println("解密：" + decryptRSADefault);
        return RetResponse.makeOKRsp().setData(decryptRSADefault);
    }

    @ResponseBody
    @RequestMapping("/getPulbicKeySm2")
    public String getPublicKeySm2() {
        return pubKeySm2;
    }

    @RequestMapping("/decryptSm2")
    @ResponseBody
    public RetResult decryptSm2(String encrypt) throws Exception {
        SM2 sm2 = SmUtil.sm2(priKeySm2, pubKeySm2);
        String decData = new String(sm2.decrypt(Hex.decodeHex("04" + encrypt)));
        System.out.println("解密：" + decData);
        return RetResponse.makeOKRsp().setData(decData);
    }

    @ResponseBody
    @RequestMapping("/getPulbicKey")
    public String getPublicKey() throws IOException {
        RSA rsa = new RSA();
        //Resource resource = new ClassPathResource("keys/secret_key.txt");
        File             file = ResourceUtils.getFile("classpath:keys/secret_key.txt");
        Properties       pro  = new Properties();//创建集合
        FileOutputStream out  = null;
        try {
            // pro.setProperty(privateKey, rsa.getPrivateKeyBase64());
            // pro.setProperty(publicKey, rsa.getPublicKeyBase64());

            pro.setProperty(privateKey, priKey);
            pro.setProperty(publicKey, pubKey);

            // log.info("public key：：：{}", rsa.getPublicKeyBase64());
            // log.info("private key：：：{}", rsa.getPrivateKeyBase64());


            log.info("public key：：：{}", pubKey);
            log.info("private key：：：{}", priKey);

            out = new FileOutputStream(file);
            pro.store(out, "密钥");
            out.flush();

        } catch (Exception e) {
            log.error("流异常：：：{}", e);
        } finally {
            pro.clear();
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("流异常", e);
                }
            }
        }
        // return rsa.getPublicKeyBase64() ;
        return pubKey;
    }

}
